package com.codingday.app;

import java.util.ArrayList;
import java.util.List;

import com.codingday.app.MyLocation.LocationResult;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Typeface;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class TODONowList extends MapActivity {

	ArrayList<Integer> todoIDArray = null;
	//ArrayList<TODO> nowTODOList = null;
	ViewFlipper mFlipper;
	Animation pushLeftIn;// = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
	Animation pushLeftOut;// =  AnimationUtils.loadAnimation(this, R.anim.push_left_out);
	Animation pushRightIn;// = AnimationUtils.loadAnimation(this, R.anim.push_right_in);
	Animation pushRightOut;
	 
	TextView tv_todonow_count;
	MapView googleMap;
	MapController mc;
	List<Overlay> mapOverlays;
	int childViewCount = 0;
	
	MyLocation myLocation = null;
	LocationResult locationResult = null;
	Location currentLocation = null;
	
	// Service Connection
	private static ServiceConnection mConnection = null;
	private static GeoAlarmService mService = null;
	
	static TODONowList instance;
	
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		
		
		Intent intent = getIntent();
		boolean fromNotification = intent.getBooleanExtra("fromNotification", false);
		todoIDArray = intent.getIntegerArrayListExtra("positions");
		if(todoIDArray == null){
			Log.i("TODONowList","positionArray is null");
		}
		
		if(fromNotification){
			Log.i("TODOView","This is From Notifiaction Service");
		    NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		    
		    // Cancel Notification
		    nm.cancel(R.string.local_service_started);
		}else{
			Log.i("TODOView", "This is not From Notification");
		}
		
		Log.i("TODONowList","Total TODO : "+todoIDArray.size());
		//Log.i("TODONowList","first :" + TODOListManager.getTODOList().get(todoIDArray.get(0)).getTitle());
		setContentView(R.layout.todo_now_list);
		
		pushLeftIn = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
		pushLeftOut =  AnimationUtils.loadAnimation(this, R.anim.push_left_out);
		pushRightIn = AnimationUtils.loadAnimation(this, R.anim.push_right_in);
		pushRightOut = AnimationUtils.loadAnimation(this, R.anim.push_right_out);
		initViewFlipper();
		
		tv_todonow_count = (TextView) findViewById(R.id.todo_now_text);
		if(todoIDArray.size() == 1){
			tv_todonow_count.setText("You have a quest near hear");
		}else{
			tv_todonow_count.setText("You have "+todoIDArray.size()+" quests near hear"+"("+1+"/"+todoIDArray.size()+")");
		}
		childViewCount = 0;
		
	    
	    doConnectToGeoAlarmService();		
		
	    AdView adView = (AdView)this.findViewById(R.id.todo_now_adView);
	    adView.loadAd(new AdRequest());
		
	    instance = this;
		final ProgressDialog pd = ProgressDialog.show(this, "", this.getString(R.string.map_waiting_msg));

		initMapView();
		myLocation = new MyLocation();
		locationResult = new LocationResult(){

			@Override
			public void gotLocation(Location location) {
				// TODO Auto-generated method stub
				pd.dismiss();
				Log.i("TODONowList","gotLocation");
				initMapPosition(location);
			}
			
		};
		myLocation.getLocation(this, locationResult, 7000);
	    
	}
	
	public static TODONowList getInstance(){
		return instance;
	}
	
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	
	@Override
	protected void onResume() {
		super.onResume();
		//initMapView();
		if(currentLocation != null){
			initMapPosition2();
		}

	}
	
	
	public void initMapView(){
		googleMap = (MapView)findViewById(R.id.todo_now_map);
		googleMap.setStreetView(true);
		googleMap.setBuiltInZoomControls(true);
		mc = googleMap.getController();

		// Overlay
		mapOverlays = googleMap.getOverlays();
		mapOverlays.clear();
		for(int i = 0; i < todoIDArray.size() ;i++){
			//mapOverlays = googleMap.getOverlays(); 
			mapOverlays.add(new OverlayCircle(TODOListManager.getTODO(todoIDArray.get(i))));
		}
	}
	
	public void initMapPosition(Location location){
		
		try {
			Looper.prepare();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		Log.i("initMapPosition","Found your Location!");
		if(location == null){
			Log.i("TODOMapView","initMapPosition : location is null");
		}
		currentLocation = location;
		initMapPosition2();

	}
	
	public void initMapPosition2(){
		GeoPoint p = new GeoPoint(((int)(currentLocation.getLatitude()*1E6)), ((int)(currentLocation.getLongitude()*1E6)));
		mapOverlays.add(new OverlayYou(this,currentLocation.getLatitude(),currentLocation.getLongitude()));
		mc.animateTo(p);
		mc.setZoom(16);		
	}
	
	public void updateView(int position){
		tv_todonow_count.setText("You have "+todoIDArray.size()+" quests near hear"+"("+(position+1)+"/"+todoIDArray.size()+")");
	/*
		double todoLatitude = TODOListManager.getTODO(todoIDArray.get(position)).getLatitude();
		double todoLongitude = TODOListManager.getTODO(todoIDArray.get(position)).getLongitude();
		GeoPoint p = new GeoPoint(((int)(todoLatitude*1E6)), ((int)(todoLongitude*1E6)));
		mc.animateTo(p);
		mc.setZoom(16);
	*/
	}

	 void initViewFlipper(){
		mFlipper = (ViewFlipper) findViewById(R.id.todo_now_filpper);
		mFlipper.removeAllViews();
		//mFlipper.setL
		//mFlipper.set
		for(int i = 0 ; i < todoIDArray.size() ; i++){
			//TODONow todonow = new TODONow(this);
			//todonow.setTODO(i);
			mFlipper.addView(LayoutInflater.from(this).inflate(R.layout.todo_now_inside_custom, null), i);
			((TODONowInside)mFlipper.getChildAt(i)).setTODO(todoIDArray.get(i));
		}

		mFlipper.setOnTouchListener(new OnTouchListener(){
			float xAtDown;
			float xAtUp;
			@Override
			public boolean onTouch(View v, MotionEvent event) {

				if(v != mFlipper){
					return false;		
				}
				if(todoIDArray.size() == 1){
					return false;
				}
				
				if(event.getAction() == MotionEvent.ACTION_DOWN) {
					xAtDown = event.getX(); 
				}
				
				else if(event.getAction() == MotionEvent.ACTION_UP){
					xAtUp = event.getX(); 
					
					if( xAtUp < xAtDown ) {
						mFlipper.setInAnimation(pushLeftIn);
						mFlipper.setOutAnimation(pushLeftOut);
						mFlipper.showNext();
						if(childViewCount == todoIDArray.size()-1){
							childViewCount = 0;
						}else{
							childViewCount++;
						}
					}
					else if (xAtUp > xAtDown){
						mFlipper.setInAnimation(pushRightIn);
						mFlipper.setOutAnimation(pushRightOut);
						mFlipper.showPrevious();	
						if(childViewCount == 0){
							childViewCount = todoIDArray.size()-1;
						}else{
							childViewCount--;
						}
					}
					updateView(childViewCount);
				}		
				return true;
			}
			
		});
		
	}
	
	 
	 
	public void goToViewToDoActivity(int position){
		Intent intent = new Intent(this,TODOView.class);
		intent.putExtra("position", position);
		startActivityForResult(intent,3);
	}
	
	
	public class OverlayCircle extends Overlay{
		
		

		TODO todo;
		public OverlayCircle(TODO todo){
			this.todo = todo;
		}
		
		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			// TODO Auto-generated method stub
			super.draw(canvas, mapView, shadow);
			 Paint paint1 = new Paint();
		     Paint paint2 = new Paint();
		     Paint stroke = new Paint();

		     paint1.setARGB(30, 200, 0, 255); // a, r, g, b
		     /*
		     paint2.setARGB(20, 255, 255, 255);
		     paint2.setStyle(Style.FILL);
		     canvas.drawPaint(paint2);
		     */
		     paint2.setARGB(255, 189, 222,0);
		     paint2.setTextAlign(Paint.Align.CENTER);
		     paint2.setTextSize(20);
		     paint2.setTypeface(Typeface.DEFAULT_BOLD);
		     paint2.setStrokeWidth(2);
		     
		     stroke.setARGB(255, 0, 0,0);
		     stroke.setTextAlign(Paint.Align.CENTER);
		     stroke.setTextSize(20);
		     stroke.setTypeface(Typeface.DEFAULT_BOLD);
		     stroke.setStyle(Paint.Style.STROKE);
		     stroke.setStrokeWidth(7);
		     
		     GeoPoint geoPoint = new GeoPoint((int)(todo.getLatitude()*1E6), (int)(todo.getLongitude()*1E6)); 
		     Point pixPoint = new Point(); 
		     mapView.getProjection().toPixels(geoPoint, pixPoint); 
		     
		     int radiusR = metersToRadius(todo.getRadius(), mapView, todo.getLatitude());
		     canvas.drawCircle(pixPoint.x, pixPoint.y, radiusR, paint1);
		    
		     
		     Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ping);
		     //canvas.drawBitmap(bmp, pixPoint.x-bmp.getWidth()/2, pixPoint.y-bmp.getHeight()/2, null);   
		     canvas.drawBitmap(bmp, pixPoint.x-bmp.getWidth()/2, pixPoint.y-bmp.getHeight(), null); 
		     
		     
		     
		     canvas.drawText(todo.getTitle(), pixPoint.x, pixPoint.y+20, stroke);
		     canvas.drawText(todo.getTitle(), pixPoint.x, pixPoint.y+20, paint2);
		     
		}
	}
	
	private static int metersToRadius(float meters, MapView map, double latitude) {
	    return (int) (map.getProjection().metersToEquatorPixels(meters) * (1/ Math.cos(Math.toRadians(latitude))));         
	}
	
	
	public boolean doConnectToGeoAlarmService(){
		// Connect to Service
		if(mConnection != null){
			//unbindService(mConnection);
		}
		mConnection = new ServiceConnection(){
	
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				mService = ((GeoAlarmService.GeoAlarmBinder)service).getService();
				
				initMapView();
				Log.i("TODONowList","onServiceConnected - bound : "+mService.getServiceBoundCount());
				
				//Log.i("TODONowList",""+mService.getMyLocation().getLatitude());
			}
	
			@Override
			public void onServiceDisconnected(ComponentName name) {
				mService = null;
				Log.i("TODONowList","onServiceDisonnected");
			}
			
		};
		boolean isSuccess = bindService(new Intent(this,GeoAlarmService.class), mConnection, 0);
		Log.i("TODONowList","Serivce Connect : "+ isSuccess);
		return isSuccess;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		unbindService(mConnection);
		super.onDestroy();
	}


}
